import logging, pathlib, datetime

def get_logger(name: str, level=logging.INFO):
    """每个模块调用自己的 logger，同名单例"""
    log = logging.getLogger(name)
    if log.hasHandlers():          # 避免重复 addHandler
        return log
    log.setLevel(level)

    # 控制台
    console = logging.StreamHandler()
    console.setLevel(level)
    console.setFormatter(
        logging.Formatter(
            "[%(asctime)s.%(msecs)03d] %(name)s | %(levelname)s | %(message)s",
            datefmt="%H:%M:%S"  # 只控制「时:分:秒」部分
        )
    )

    # 文件：每天一个 log
    log_dir = pathlib.Path("logs")
    log_dir.mkdir(exist_ok=True)
    file_handler = logging.FileHandler(
        log_dir / f"{datetime.date.today()}.log", encoding="utf-8"
    )
    file_handler.setFormatter(
        logging.Formatter(
            "[%(asctime)s.%(msecs)03d] %(name)s | %(levelname)s | %(message)s",
            datefmt="%H:%M:%S"
        )
    )

    log.addHandler(console)
    log.addHandler(file_handler)
